package com.siyoumi.app.modules.account.service;

import com.siyoumi.app.entity.SysDepartment;
import com.siyoumi.app.modules.account.entity.VaSysDepartment;
import com.siyoumi.app.service.SysDepartmentService;
import com.siyoumi.component.XApp;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SvcDepartment {
    static public SvcDepartment getBean() {
        return XSpringContext.getBean(SvcDepartment.class);
    }

    static public SysDepartmentService getApp() {
        return XSpringContext.getBean(SysDepartmentService.class);
    }


    public List<Map<String, Object>> getList() {
        String[] select = {
                "dep_id",
                "dep_name",
        };
        JoinWrapperPlus<SysDepartment> query = listQuery();
        query.select(select);

        return getApp().getMaps(query);
    }

    public JoinWrapperPlus<SysDepartment> listQuery() {
        return listQuery(InputData.getIns());
    }

    /**
     * select
     *
     * @return query
     */
    public JoinWrapperPlus<SysDepartment> listQuery(InputData inputData) {
        String name = inputData.input("name");

        JoinWrapperPlus<SysDepartment> query = getApp().join();
        query.eq("dep_x_id", XHttpContext.getX())
                .eq("dep_del", 0);
        ;
        getApp().addQueryAcc(query);
        //排序
        query.orderByAsc("dep_order")
                .orderByDesc("dep_id");
        if (XStr.hasAnyText(name)) { //名称
            query.like("dep_name", name);
        }

        return query;
    }

    public XReturn edit(InputData inputData, VaSysDepartment vo) {
        List<String> ignoreField = new ArrayList<>();
        if (inputData.isAdminEdit()) {
            //ignoreField.add("fwins_acc_id");
        }

        return XApp.getTransaction().execute(status -> {
            XReturn r = getApp().saveEntity(inputData, vo, true, ignoreField);
            if (r.err()) {
                return r;
            }

            return r;
        });
    }

    /**
     * 删除
     */
    @SneakyThrows
    @Transactional(propagation = Propagation.MANDATORY)
    public XReturn delete(List<String> ids) {
        XReturn r = XReturn.getR(0);

        getApp().delete(ids);

        return r;
    }
}
